var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');


const WebSocket = require('ws')
 
 const server = new WebSocket.Server({port:8080})

 server.on('open',function open(){
     console.log('已连接')
 })

 server.on('close',function close(){
     console.log('已断开')
 })

 let clients = {}

 function transformer(data){
  return JSON.stringify(data)
 }

 function parse(data){
  let res = ''
  try {
    res = JSON.parse(data)
  } catch (error) {
    res = data
  }
  return res
 }

 server.on('connection',function connection(ws,req){
     const ip = req.socket.remoteAddress
     const port = req.socket.remotePort
     const clientName = ip + port

    
     clients[clientName] = ws
     console.log('%s 已连接 ',clientName)
     server.clients.forEach(function each(client,socket){
        if(client.readyState === WebSocket.OPEN){
            client.send(transformer({type:'list',data:Object.keys(clients)}))
        }
    })

    ws.send(clientName)

     ws.on('message',function incoming(message){
         console.log('收到: %s 来自 %s',clientName)
        //  server.clients.forEach(function each(client){
        //      if(client.readyState === WebSocket.OPEN){
        //          client.send(clientName +" -> " + message)
        //      }
        //  })

       let data =  parse(message)

       switch (data.type) {
        case 'offer':
          {
            let { id, offer } = data.data
            clients[id].send(transformer({type:'offer',data:{id:clientName,offer}}))
          }
          break;
        case 'answer':
          {
            let { id, answer } = data.data
            clients[id].send(transformer({type:'answer',data:{id:clientName,answer}}))
          }
          break;
        case 'candidate':
          {
            let { id, candidate } = data.data
            clients[id].send(transformer({type:'candidate',data:{id:clientName,candidate}}))
          }
          break;
        default:
          break;
       }
      

     })



 })












var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const { log } = require('console');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);



// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
